const express = require('express')
const app = express()


app.use((req,res,next)=>{
  const allowAdd =['http://localhost:63340','http://localhost:63341','http://localhost:63342','http://localhost:63343']
  // console.log(req)
  // console.log(req.origin)
  // console.log(req.[Symbol(kHeaders)].origin)
  // console.log(req.headers.origin)
  if (allowAdd.includes(req.headers.origin)){
    res.set('Access-Control-Allow-Origin',req.headers.origin)
    res.set('Access-Control-Allow-headers','token')
  }
  next()
})
app.get('/corsGet',(req,res)=>{
  const{userId} = req.query

  if (userId!=='001'){
    res.send({
      code:10001,
      msg:'查询失败，ID不存在或错误',
      data:null
    })
  }

  res.send({
    userId:'001',
    msg:'查询成功',
    code:10000,
    data:{
      name:'万登豪',
      age:18,
      sex:'man'
    }
  })
})

//jsonP方案决绝跨域问题
app.get('/JsonPGet',(req,res)=>{
  const {userId,name,cb} = req.query
  // console.log('userId',userId)
  // console.log('name',name)
  // console.log('cb',cb)
  const data = {
    code: 10000,
    msg: "查询成功",
    data: {
      name: "万登豪",
      age: 18,
      sex: "男"
    }
  }
  res.send(`
    ${cb}(Promise.resolve(${JSON.stringify(data)}))
  `)
})


app.listen(8090,()=>{
  console.log('running!!!!!!!!')
})